package com.cskaoyan.service.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.admin.vo.*;
import com.cskaoyan.bean.wx.vo.UserIdVo;
import com.cskaoyan.bean.wx.vo.UserRegister;
import com.cskaoyan.bean.wx.vo.WxFeedbackSubmit;
import com.cskaoyan.bean.wx.vo.WxFootPrintVO;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.UserService;
import com.cskaoyan.utils.CommonUtil;
import com.cskaoyan.utils.Constant;
import com.cskaoyan.utils.MarketPageUtil;
import com.github.pagehelper.PageHelper;
import com.sun.mail.imap.protocol.ID;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author tangjian
 * @Date 2021/10/18 20:59
 * @description
 */

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired

    UserMapper userMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    CollectMapper collectMapper;
    @Autowired
    FootprintMapper footprintMapper;
    @Autowired
    FeedbackMapper feedbackMapper;
    @Autowired
    SearchHistoryMapper searchHistoryMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    GoodsMapper goodsMapper;


    @Override
    public BasePageData query(String username, String mobile, BaseParam param) {

        //配置分页
        PageHelper.startPage(param.getPage(), param.getLimit());

        UserExample userExample = new UserExample();
        userExample.setDistinct(false);

        //构造条件 保证参数不为空
        UserExample.Criteria criteria = userExample.createCriteria();
        if (username != null && !username.equals("")) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (mobile != null && !mobile.equals("")) {
            criteria.andMobileLike("%" + mobile + "%");
        }

        //设置排序
        userExample.setOrderByClause(param.getSort() + " " + param.getOrder());

        //查询
        List<User> userList = userMapper.selectByExample(userExample);

        //分页结果接收 内置在BasePageData中
        return BasePageData.ok(userList);

    }


    @Override
    public BaseRespVo query(Integer id) {

        User user = userMapper.selectByPrimaryKey(id);

        return BaseRespVo.ok(user);
    }

    @Override
    public BasePageData addressQuery(String name, Integer userid, BaseParam param) {
        //分页配置
        MarketPageUtil.startPage(param);

        //条件配置
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();

        if (userid != null && userid > 0) {
            criteria.andUserIdEqualTo(userid);
        }
        if (name != null && !name.equals("")) {
            criteria.andNameLike("%"+name+"%");
        }

        //设置排序
        addressExample.setOrderByClause(param.getSort() + " " + param.getOrder());

        //查询
        List<Address> addressList = addressMapper.selectByExample(addressExample);

        //分页结果接收 内置在BasePageData中
        return BasePageData.ok(addressList);

    }

    @Override
    public BasePageData collectQuery(Integer valueid, Integer userid, BaseParam param) {
        //分页配置
        MarketPageUtil.startPage(param);

        //条件配置
        CollectExample collectExample = new CollectExample();
        CollectExample.Criteria criteria = collectExample.createCriteria();

        if (valueid != null && valueid > 0) {
            criteria.andUserIdEqualTo(valueid);
        }
        if (userid != null && userid > 0) {
            criteria.andUserIdEqualTo(userid);
        }

        //设置排序
        collectExample.setOrderByClause(param.getSort() + " " + param.getOrder());

        //查询
        List<Collect> collects = collectMapper.selectByExample(collectExample);

        //分页结果接收 内置在BasePageData中
        return BasePageData.ok(collects);
    }

    @Override
    public BasePageData footprintQuery(Integer userId, Integer goodsId, BaseParam param) {

        //分页配置
        MarketPageUtil.startPage(param);

        //条件配置
        FootprintExample footprintExample = new FootprintExample();
        FootprintExample.Criteria criteria = footprintExample.createCriteria();

        if (userId != null && userId > 0) {
            criteria.andUserIdEqualTo(userId);
        }
        if (goodsId != null && goodsId > 0) {
            criteria.andGoodsIdEqualTo(goodsId);
        }

        //设置排序
        footprintExample.setOrderByClause(param.getSort() + " " + param.getOrder());

        //查询
        List<Footprint> footprints = footprintMapper.selectByExample(footprintExample);

        //分页结果接收 内置在BasePageData中
        return BasePageData.ok(footprints);
    }

    @Override
    public BasePageData historyQuery(Integer userId, String keyword, BaseParam param) {

        MarketPageUtil.startPage(param);

        SearchHistoryExample searchHistoryExample = new SearchHistoryExample();
        SearchHistoryExample.Criteria criteria = searchHistoryExample.createCriteria();

        if (userId != null && userId > 0) {
            criteria.andUserIdEqualTo(userId);
        }
        if (keyword != null && !keyword.equals("")) {
            criteria.andKeywordLike("%" + keyword + "%");
        }

        searchHistoryExample.setOrderByClause(param.getSort() + " " + param.getOrder());
        List<SearchHistory> searchHistories = searchHistoryMapper.selectByExample(searchHistoryExample);

        return BasePageData.ok(searchHistories);
    }

    @Override
    public BasePageData feedbackQuery(String username, Integer id, BaseParam param) {

        MarketPageUtil.startPage(param);

        FeedbackExample feedbackExample = new FeedbackExample();
        FeedbackExample.Criteria criteria = feedbackExample.createCriteria();

        if (username != null && !username.equals("")) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (id != null && id > 0) {
            criteria.andIdEqualTo(id);
        }

        feedbackExample.setOrderByClause(param.getSort() + " " + param.getOrder());

        List<Feedback> feedbacks = feedbackMapper.selectByExample(feedbackExample);

        return BasePageData.ok(feedbacks);
    }

    @Override
    public int update(User user) {

        int i = userMapper.updateByPrimaryKeySelective(user);
        return i;
    }

    @Override
    public DashboardVo selectDashboard() {
        int goodsTotal = userMapper.selectGoodsTotal();
        int userTotal = userMapper.selectUserTotal();
        int productTotal = userMapper.selectProductTotal();
        int orderTotal = userMapper.selectOrderTotal();
        DashboardVo dashboardVo = new DashboardVo();
        dashboardVo.setGoodsTotal(goodsTotal);
        dashboardVo.setUserTotal(userTotal);
        dashboardVo.setProductTotal(productTotal);
        dashboardVo.setOrderTotal(orderTotal);
        return dashboardVo;
    }

    @Override
    public UserStatisticsVo selectUserStatistics() {

        List<DateTimeVo> dateTimeVoList = userMapper.selectUserGroupByAddTime();
        List<UserStatisticsRowsVo> userStatisticsRowsVos = new ArrayList<>();


        for (DateTimeVo dateTimeVo : dateTimeVoList) {
            //日期为同一天
            Date add_time = dateTimeVo.getAdd_time();
            List<UserIdVo> idVos = userMapper.selectUsersByTime(add_time);
            //同一天的用户数量
            Integer users = idVos.size();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String day = simpleDateFormat.format(add_time);
            userStatisticsRowsVos.add(new UserStatisticsRowsVo(day, users));
        }

        String[] columns = new String[2];
        columns[0] = "day";
        columns[1] = "users";

        UserStatisticsVo userStatisticsVo = new UserStatisticsVo(columns, userStatisticsRowsVos);

        return userStatisticsVo;
    }

    @Override
    public OrderStatisticsVo selecOrderStatistics() {

        String[] strings = new String[4];
        strings[0] = "day";
        strings[1] = "orders";
        strings[2] = "customers";
        strings[3] = "pcr";

        List<OrderStatisticsRowsVo> orderStatisticsRowsVos = new ArrayList<>();
        //订单总金额

        //日期分组
        List<DateTimeVo> dateTimeVos = orderMapper.selectOrderGroupByTime();
        for (DateTimeVo dateTimeVo : dateTimeVos) {
            Date add_time = dateTimeVo.getAdd_time();
            List<Order> orderList = orderMapper.selectPriceGroupByTime(add_time);
            //订单量
            Integer orders = orderList.size();
            Set<String> count = new HashSet<>();
            //下单用户
            Integer customers = 0;
            Double amount = 0.0;
            BigDecimal a = new BigDecimal(amount);
            for (Order order : orderList) {
                BigDecimal goodsPrice = order.getGoodsPrice();
                Integer userId = order.getUserId();
                User user = userMapper.selectByPrimaryKey(userId);
                String username = user.getUsername();
                count.add(username);
                customers = count.size();
                a = a.add(goodsPrice);
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String day = simpleDateFormat.format(add_time);
            orderStatisticsRowsVos.add(new OrderStatisticsRowsVo(a, orders, customers, day, a));
        }

        OrderStatisticsVo orderStatisticsVo = new OrderStatisticsVo(strings, orderStatisticsRowsVos);

        return orderStatisticsVo;
    }

    @Override

    public User selectPwdByUserName(String username) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria().andUsernameEqualTo(username);

        List<User> users = userMapper.selectByExample(userExample);

        return users.size() != 0 ? users.get(0) : null;
    }

    @Override
    public boolean userIsExist(String username) {

        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);

        long l = userMapper.countByExample(userExample);

        return l > 0;
    }

    @Override
    public int wxRegisterUserInsert(UserRegister register) {
        User user = new User();
        user.setAddTime(new Date());
        user.setUsername(register.getUsername());
        user.setPassword(register.getPassword());
        user.setMobile(register.getMobile());
        user.setWeixinOpenid(register.getWxCode());
        //昵称先存 用户名
        user.setNickname(register.getUsername());
        String host = SecurityUtils.getSubject().getSession().getHost();
        user.setLastLoginIp(host);

        int i = userMapper.insertSelective(user);

        return i;
    }

    @Override
    public List<Address> addressQuery(Integer userId) {
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<Address> addresses = addressMapper.selectByExample(addressExample);
        return addresses;
    }

    @Override
    public int addressInsert(Address address) {

        int i = addressMapper.insertSelective(address);
        return i;
    }

    @Override
    public int addressDefaultCancel() {
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        criteria.andIsDefaultEqualTo(true);
        Address address = new Address();
        address.setIsDefault(false);
        int i = addressMapper.updateByExampleSelective(address, addressExample);

        return i;
    }

    @Override
    public int addressDelete(Integer id) {

        int i = addressMapper.deleteByPrimaryKey(id);
        return i;
    }

    @Override
    public int footprintDelete(Integer id) {

        int i = footprintMapper.deleteByPrimaryKey(id);
        return i;
    }

    @Override
    public int feedbackInsert(WxFeedbackSubmit wxFeedbackSubmit, User user) {

        Feedback feedback = new Feedback();
        feedback.setMobile(wxFeedbackSubmit.getMobile());
        feedback.setFeedType(wxFeedbackSubmit.getFeedType());
        feedback.setContent(wxFeedbackSubmit.getContent());
        feedback.setHasPicture(wxFeedbackSubmit.getHasPicture());
        if (wxFeedbackSubmit.getHasPicture() != null) {
            feedback.setHasPicture(true);
            feedback.setPicUrls(wxFeedbackSubmit.getPicUrls());
        } else {
            feedback.setHasPicture(false);
        }
        feedback.setAddTime(new Date());
        feedback.setUserId(user.getId());
        feedback.setUsername(user.getUsername());

        int insert = feedbackMapper.insertSelective(feedback);

        return insert;
    }


    public int insert(User user) {
        Integer integer = userMapper.selectByMobile(user.getMobile());
        if (integer != null) {
            return 0;
        } else {
            user.setAddTime(CommonUtil.nowTime());
            user.setUpdateTime(CommonUtil.nowTime());
            user.setGender(Constant.GENDER);
            user.setLastLoginTime(CommonUtil.nowTime());
            user.setUserLevel(Constant.USER_LEVEL);
            user.setAvatar(Constant.NICK);
            user.setSessionKey(Constant.NICK);
            user.setStatus(Constant.STATUS);
            user.setDeleted(false);
            int insert = userMapper.insert(user);
            return insert;
        }
    }

    @Override
    public int updateInWechat(User user) {
        Integer integer = userMapper.selectByMobile(user.getMobile());
        user.setLastLoginTime(CommonUtil.nowTime());
        if (integer == null) {
            return 0;
        } else {
            user.setId(integer);
            return userMapper.updateByPrimaryKey(user);
        }
    }

    @Override
    public BasePageData listFootprint(Integer userId, BaseParam baseParam) {

        PageHelper.startPage(baseParam.getPage(), baseParam.getLimit());

        FootprintExample footprintExample = new FootprintExample();
        FootprintExample.Criteria criteria = footprintExample.createCriteria();

        if (userId != null && !"".equals(userId)) {
            criteria.andUserIdEqualTo(userId);
        }
        footprintExample.setOrderByClause("update_time"+" desc");
        List<Footprint> footprints = footprintMapper.selectByExample(footprintExample);
        ArrayList<WxFootPrintVO> wxFootPrintVOS = new ArrayList<>();

        for (Footprint footprint : footprints) {
            Integer goodsId = footprint.getGoodsId();
            Goods goods = goodsMapper.selectByPrimaryKey(goodsId);

            WxFootPrintVO wxFootPrintVO = new WxFootPrintVO();
            wxFootPrintVO.setAddTime(footprint.getAddTime());
            wxFootPrintVO.setGoodsId(goodsId);
            wxFootPrintVO.setId(footprint.getId());
            if(goods != null){
                wxFootPrintVO.setRetailPrice(goods.getRetailPrice().doubleValue());
                wxFootPrintVO.setPicUrl(goods.getPicUrl());
                wxFootPrintVO.setName(goods.getName());
                wxFootPrintVO.setBrief(goods.getBrief());
            }
            wxFootPrintVOS.add(wxFootPrintVO);
        }

        return BasePageData.ok(wxFootPrintVOS);
    }

    @Override
    public boolean phoneIsExist(String mobile) {

        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andMobileEqualTo(mobile);

        long l = userMapper.countByExample(userExample);

        return l > 0;
    }

    @Override
    public User updatePwdByMobile(String mobile, String pwd) {

        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andMobileEqualTo(mobile);
        User user = new User();
        user.setPassword(pwd);
        userMapper.updateByExampleSelective(user, userExample);


        List<User> users = userMapper.selectByExample(userExample);

        if (users != null) {
            user = users.get(0);
        }

        return user;
    }

}
